package org.nViron.Graffiti;

import instar.dg.Common.ID;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import instar.dg.Profile.Friend;
import instar.dg.Profile.FriendListener;

public class FriendManager implements FriendListener, Serializable {

    private List<Friend> friendsList;
    private GraffitiSource GraffitiSource;
    private boolean dirty = true;

    public FriendManager(GraffitiSource manager) {
        friendsList = new ArrayList<Friend>();
        this.GraffitiSource = manager;
    }

    public List<Friend> getFriendsList() {
        return friendsList;
    }

    @Override
    public void addFriend(Friend f) {
        friendsList.add(f);
        dirty = true;
    }

    @Override
    public void deleteFriend(Friend f) {
        friendsList.remove(f);
        dirty = true;
    }

    @Override
    public void permissionUpdateReplyReceived() {
    }

    //friend went offline
    @Override
    public void removeFriend(Friend f) {
        //substitute old friend object with new one
        if (friendsList.contains(f)) {
            friendsList.set(friendsList.indexOf(f), f);
            dirty = true;

            GraffitiSource.remove(f.getId());
        }
    }

    @Override
    public void updateFriend(Friend f) {
        if (friendsList.contains(f)) {
            friendsList.set(friendsList.indexOf(f), f);
            dirty = true;
        }
        // TODO find a better way to update a friend
        GraffitiSource.remove(f.getId());
        GraffitiSource.addFriend(f);
    }

    public void SetDirty(boolean bool) {
        dirty = bool;
    }

    public boolean isDirty() {
        return dirty;
    }

    public Friend getFriend(ID friendId) {
        for (Friend f : friendsList) {
            if (f.getId().equals(friendId)) {
                return f;
            }
        }
        return null;
    }
}
